/* Includes ------------------------------------------------------------------*/
#include "stm32f10x_conf.h"
#include "Sound.h"
#include "Cuckoo.h"

/* Exported functions --------------------------------------------------------*/

// Sound_Init()
// ------------
// Initialize the sound module.
extern void Sound_Init()
{
	/* Enable the GPIOA, AFIO, DAC, TIM6 and DMA2 clocks ---------------------*/
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA2, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6 | RCC_APB1Periph_DAC, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOA, ENABLE);

	/* Configure the GPIO ----------------------------------------------------*/
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	/* Configure the DAC -----------------------------------------------------*/
	DAC_DeInit();
	DAC_InitTypeDef DAC_InitStructure;
	DAC_StructInit(&DAC_InitStructure);
	DAC_InitStructure.DAC_Trigger = DAC_Trigger_T6_TRGO;
	DAC_Init(DAC_Channel_1, &DAC_InitStructure);

	/* Enable DAC Channel1 ---------------------------------------------------*/
	DAC_Cmd(DAC_Channel_1, ENABLE);

	//  Once the DAC channel1 is enabled, PA.04 is automatically connected to the DAC converter.

	/* TIM6 Configuration ----------------------------------------------------*/
	TIM_DeInit(TIM6);

	/* TIM6 TRGO selection ---------------------------------------------------*/
	TIM_SelectOutputTrigger(TIM6, TIM_TRGOSource_Update);

	/* Set TIM6 frequency ----------------------------------------------------*/
	TIM_SetAutoreload(TIM6, 9000); // 72MHz / 8KHz = 9000

	/* Start TIM6 ------------------------------------------------------------*/
	TIM_Cmd(TIM6, ENABLE);
}

// Sound_Play()
// ------------
// Play the sound file once.
extern void Sound_Play()
{
	/* DMA1 channel3 configuration */
	DMA_DeInit(DMA2_Channel3);
	DMA_InitTypeDef DMA_InitStructure;
	DMA_StructInit(&DMA_InitStructure);
	DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&DAC->DHR8R1;
	DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t) &Sound_Buffer;
	DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
	DMA_InitStructure.DMA_BufferSize = sizeof(Sound_Buffer);
	DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
	DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
	//DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Word;//DMA_PeripheralDataSize_Byte;
	//DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;//DMA_MemoryDataSize_Byte;
	//DMA_InitStructure.DMA_Mode = DMA_Mode_Normal; //DMA_Mode_Circular;
	//DMA_InitStructure.DMA_Priority = DMA_Priority_High;
	//DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
	DMA_Init(DMA2_Channel3, &DMA_InitStructure);

	/* Enable DMA2 Channel3 */
	DMA_Cmd(DMA2_Channel3, ENABLE);

	/* Enable DMA for DAC Channel1 -------------------------------------------*/
	DAC_DMACmd(DAC_Channel_1, ENABLE);
}
